<?php

namespace App\Models;

use App\Http\Controllers\Resource\BkController;
use App\Http\Controllers\Resource\ZwzxController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/*数字资源（博看）model*/

class ResourceBk extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_bk';

    /*关联活动类型*/
    public function conBigType()
    {
        return $this->hasOne(ResourceType::class, 'id', 'big_type_id');
    }


    /*关联活动类型*/
    public function conType()
    {
        return $this->hasOne(ResourceTypeExternal::class, 'id', 'type_id');
    }


    /**
     * 获取书籍详情
     * @param id  书籍id
     * @param guid  书籍guid  和 书籍id 2选一
     * @param resource_business_id  资源商id
     */
    public function detail($id = null, $guid = null)
    {
        if (empty($id) && empty($guid)) {
            return false;
        }
        $res = $this->select([
            'id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'issue_name',
            'issue_year',
            'press',
            'pre_time',
            'img',
            'intro',
            'create_time',
            'big_type_id',
            'type_id',
            'browse_num',
            'is_recom'
        ])->with('conBigType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->with('conType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->where(function ($query) use ($id, $guid) {
            if ($id) {
                $query->where('id', $id);
            } else {
                $query->where('guid', $guid);
            }
        })->where('is_del', 1)
            ->first();
        if ($res) {
            if ($res->big_type_id == 4 && (strlen($res->isbn) == 8 || strlen($res->isbn) == 9)) {
                $res->isbn = substr($res->isbn, 0, 4) . '-' . substr($res->isbn, 4); //issn号加横线
            }
            $is_exists_chapter = ResourceBusinessName::where('id', $res->resource_business_id)->value('is_exists_chapter');
            $res->is_exists_chapter = $is_exists_chapter == 1 ? true : false; //是否存在章节，有则可以获取
        }
        return $res;
    }

    /**
     * 添加数据到数据库
     * @param $data
     */
    public function addData($data)
    {
        if (empty($data['resourceId'])) {
            return false;
        }

        $res = $this->where('data_unique_id', $data['resourceId'])->first(); //获取所有数据，之前下架的现在重新上架
        if (empty($res)) {
            //修改
            $res = new self();
            $guid = get_guid();
            $res->guid = $guid;
        }
        $res->data_unique_id = $data['resourceId'];
        $res->resource_business_id = 4;
        $res->big_type_id = $data['big_type_id'];
        $res->type_id = $data['type_id'];
        $res->press = $data['press'];
        $res->pre_time = $data['publish'];
        $res->img = $data['img'];
        $res->intro = $data['intro'];
        $res->link = $data['url'] ?? '';

        if ($data['big_type_id'] == 1) {
            //电子书
            $res->title = $data['bookname'];
            $res->author = $data['author'];
            $res->isbn = str_replace('-', '', $data['isbn']);
        } else {
            //期刊
            $res->title = $data['magazinename'];
            $res->issue_name = $data['issueName']; //期号，不是期刊号
            $res->issue_year = $data['issueYear']; //期号，年份
            $res->author = ''; //无作者
            $res->isbn = str_replace(['-', 'ISSN'], '', $data['issn']);
        }
        $res->change_time = date('Y-m-d H:i:s'); //数据唯一id
        $res->is_del = 1;
        $res->save();

        //加入到资源总数据库
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->addData($res);

        return $res->id;
    }


    /**
     *删除下架数据
     */
    public function deleteData($type_id, $data_unique_id_all)
    {
        $data_guid_all = $this->whereNotIn('data_unique_id', $data_unique_id_all)->where('type_id', $type_id)->where('is_del', 1)->pluck('guid')->toArray(); //bid 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($data_guid_all)) {
            return true;
        }
        $this->whereIn('guid', $data_guid_all)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);

        //删除总数据
        foreach ($data_guid_all as $key => $val) {
            $resourceTotalModel = new ResourceTotal();
            $resourceTotalModel->deleteData($val);
        }
        return true;
    }

    /**
     * 获取图书阅读地址，单点登录进行阅读
     * @param user_id  用户id  实际是用户token
     * @param guid  资源guid
     */
    public function getBkSingleSign($user_id, $guid)
    {
        $book_info = $this->select('link')->where('guid', $guid)->where('is_del', 1)->first();
        if (empty($book_info)) {
            return false;
        }
        if (empty($book_info['link'])) {
            return false;
        }
        $bkObj = new BkController();
        $res = $bkObj->singleSign($user_id, $book_info['link']);
        $data['link'] = $res;
        return $data;
    }
}
